package org.example.DataStructure.Queue;

//队列的实现
public class Queue<T> {
    //成员变量,头节点，尾节点，队列中元素个数
    private Node<T> head;
    private Node<T> tail;
    private int size;

    //节点内部类
    private class Node<T> {
        private T data;
        private Node<T> next;

        //构造方法
        public Node(T data, Node<T> next) {
            this.data = data;
            this.next = next;
        }
    }

    //构造方法
    public Queue() {
        //初始化头节点
        this.head = null;
        //初始化尾节点
        this.tail = null;
        //初始化元素数量
        this.size = 0;
    }

    //判断队列是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    //获取队列中元素的个数
    public int size() {
        return size;
    }

    //出队，从头节点出
    public T dequeue() {
        if (isEmpty()) {
            return null;
        }
        //记录数据
        T data = head.data;
        //改变头节点指针
        head = head.next;
        //元素数量-1
        size--;
        return data;
    }

    //入队，从尾节点入
    public void enqueue(T data) {
        if (isEmpty()) {
            head = tail = new Node<>(data, null);
        } else {
            tail.next = new Node<>(data, null);
            tail = tail.next;
        }
        //元素数量+1
        size++;
    }

    //获取队头元素而不删除的方法
    public T peek() {
        if (isEmpty()) {
            return null;
        }
        return head.data;
    }

    //重写ToString方法
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("队头 [");
        Node<T> current = head;
        while (current != null) {
            sb.append(current.data);
            sb.append(" ");
            current = current.next;
        }
        sb.append("] 队尾");
        return sb.toString();
    }
}
